package com.javaAdmin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.javaAdmin.util.ObjectUtils;
import com.javaAdmin.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.plaf.multi.MultiInternalFrameUI;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/upload")

public class UploadController {


    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/img")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            Result.fail("请选择上传文件");
        }
        //文件名
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);

        // 获取文件后缀
        String suffix = FileUtil.getSuffix(fileName);
        System.out.println(suffix);

        // 对文件名进行重命名
        // 年/月/日/当前时间/时间戳-uuid.jpg

        // 文件子路径
        String url = ObjectUtils.generateFileByTime() + ObjectUtils.generateFileBySecond() + "-" + ObjectUtils.generateUuId() + StrUtil.DOT + suffix;
        // 文件上传的一个真实路径
        String filePath = uploadPath + url;
        InputStream inputStream = file.getInputStream();
        FileUtil.writeFromStream(inputStream, filePath);

        return Result.success(url);
    }
}
